<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>取消请求</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    </head>
    <body>
        <button>发送请求</button>
        <button>取消请求</button>
        <script>
            // xhr.abort
            // 1. 声明一个变量
            let cancel; //取消

            let btns = document.querySelectorAll("button");
            btns[0].onclick = async function () {
                //取消之前的请求
                if(cancel) {
                    cancel();
                }
                let res = await axios({
                    url: "http://127.0.0.1:8090/delay-server",
                    //2. 设置取消请求的属性
                    cancelToken: new axios.CancelToken(
                        (c) => {
                            cancel = c;
                        }
                    ),
                });
                console.log(res);
            };

            btns[1].onclick = function () {
                //3. 取消请求
                cancel();
            };
        </script>
    </body>
</html>
